package com.coolwen.controller;

import com.alibaba.fastjson.JSON;
import com.coolwen.entity.User;
import com.coolwen.service.UserService;
import com.coolwen.service.UserServiceImpl;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by user on 2016/4/26.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    //    UserService userService;
    @Autowired
    UserService userService;

    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    public String showUserInfo(ModelMap modelMap, @PathVariable String userId) {
        User u = userService.getUserById(userId);
        System.out.print(u.getUserName());
        modelMap.addAttribute("user", u);
        return "/user/showInfo";
    }

    @RequestMapping(value = "/usersjson")
    public
    @ResponseBody
    Object showUserInfos() {
        List<User> userInfos = userService.selectAllUser();
//        PageInfo<User> userInfos = userService.queryByPage(null, 1, 2);
        return userInfos;
    }

    @RequestMapping(value = "/users")
    public String list(Model model) {
        List<User> userInfos = userService.selectAllUser();
        model.addAttribute("users", userInfos);
        return "/user/list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute(new User());
        return "/user/add";

    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@Validated User user, BindingResult br, @RequestParam("attachs") MultipartFile[] attachs, HttpServletRequest req) {
        if (br.hasErrors()) {
            //如果有错误直接跳转到add视图
            return "/user/add";
        }
        String realPath = req.getSession().getServletContext().getRealPath("/resources/upload");
//        System.out.print(realPath);
        for (MultipartFile attach : attachs) {
            if (attach.isEmpty())
                continue;
            File f = new File(realPath + "/" + attach.getOriginalFilename());
            try {
                FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        userService.insert(user);
        return "redirect:/user/users";

    }


    @RequestMapping(value = "/{userId}/update", method = RequestMethod.GET)
    public String update(@PathVariable String userId, Model model) {
        User u = userService.getUserById(userId);
        //       System.out.print(u.getUserName());
        model.addAttribute("user", u);
        return "/user/update";
    }

    @RequestMapping(value = "/{userId}/update", method = RequestMethod.POST)
    public String update(@Validated User user, BindingResult br) {
        if (br.hasErrors()) {
            return "/user/update";
        }
        userService.updateByPrimaryKeySelective(user);
        return "redirect:/user/users";
    }

    @RequestMapping(value = "/{userId}/delete", method = RequestMethod.GET)
    public String delete(@PathVariable String userId) {
        User u = userService.getUserById(userId);
        System.out.print(u.getUserName());
        userService.deleteByPrimaryKey(Long.parseLong(userId));
        return "redirect:/user/users";
    }

    /**
     * 分页查询用户信息
     *
     * @param
     * @return
     * @author linbingwen
     * @since 2016年5月10日
     * http://localhost:8080/user/list?userName=wen&pageNumber=1&pageSize=3
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public
    @ResponseBody
    Object list(String userName,
                @RequestParam(required = false, defaultValue = "1") int pageNumber,
                @RequestParam(required = false, defaultValue = "10") int pageSize) {
        try {
            PageInfo<User> pageResult = userService.queryByPage(userName, pageNumber, pageSize);
            return pageResult;
        } catch (Exception e) {
            return e.getMessage();
        }

    }

    /**
     * 显示首页
     *
     * @return
     * @author linbingwen
     * @since 2015年10月23日
     */
    @RequestMapping("/home")
    public String bootStrapTest1() {
        return "user/home";
    }


    @RequestMapping(value = "/listuser", method = RequestMethod.GET)
    public String getList(String userName, Model model,
                          @RequestParam(required = false, defaultValue = "1") int page,
                          @RequestParam(required = false, defaultValue = "10") int rows) {
        PageInfo<User> pageResult = userService.queryByPage(userName, page, rows);
        model.addAttribute("pageInfo", pageResult);


        return "user/home";
    }
}
